<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    
    <style>
      .block {
        color: black;
      }
      
      .red {
        color: red;
      }
      
      .green {
        color: green;
      }
    </style>
  </head>
  <body>
    <div style="width: 500px;height: 200px;background: pink;display: flex;flex-flow:column;align-items: center">
      <h3>打字练习</h3>
      <h2 id="content"></h2>
      <input id="input" type="text" onkeydown="return keydown()"/><!--return与禁用相关-->
      
      <div>
        总字数：<span id="zong"></span>
        正确数：<span id="dui"></span>
      </div>
      
      <input type="button" value="背景音乐" style="position: absolute;left: 20px;top: 20px" onclick="play()"/>
      <audio id="music" autoplay="autoplay" src="./static/typewriting.mp3"></audio>
    </div>
  </body>
  
  <script>
    // 1.加载内容到html内展示，由于接下来需要对比每个输入是否相同采取id编号的方式
    let content = 'hello.welcome to study center!';
    
    let str = '';
    for (let i = 0; i < content.length; i++) {
      str += '<span id=\'my-span' + i + '\' class=\'black\'/>' + content.substring(i, i + 1) + '</span>';
    }
    document.getElementById('content').innerHTML = str;
    
    document.getElementById('zong').innerText = 0;
    document.getElementById('dui').innerText = 0;
    
    // 2.输入
    //全局参数记录
    let index = -1;//当前输入位置
    let dui = -1;//正确数量
    function keydown(event) {
      event = event || window.event;
      let keyCode = event.keyCode;//输入的字码
      let keyStr = String.fromCharCode(keyCode);//输入的字符
      
      if ((index <= -1 && keyCode == 8) || (index >= content.length - 1 && keyCode != 8)) {
        return false;
      }
      
      if (index >= 0 && keyCode == 8) {//如果是删除键
        if (document.getElementById('my-span' + index).className == 'green') {
          dui--;
        }
        document.getElementById('my-span' + index).className = 'block';
        index--;
      } else {
        index++;
        
        //忽略大小写
        if (keyCode >= 65 && keyCode <= 90) {//是大写字符
          keyCode += 32;//得到小写
          keyStr = String.fromCharCode(keyCode);
        } else {//其他，。之类
          keyStr = String.fromCharCode(keyCode - 144);
        }
        
        let curChar = content.charAt(index);//正确字符
        if (curChar == keyStr) {//输入正确
          document.getElementById('my-span' + index).className = 'green';
          dui++;
        } else {//输入错误
          document.getElementById('my-span' + index).className = 'red';
        }
      }
      document.getElementById('zong').innerText = index + 1;
      document.getElementById('dui').innerText = dui + 1;
    }
    
    // 3.播放背景音乐：为了防止移动端的宽带和扰民，阻止了自动播放，只要用户和界面有交互就会开始播放
    function play() {
      document.getElementById('music').play();
    }
  </script>
</html>